package com.usian.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.usian.common.aliyun.OSSService;
import com.usian.common.dtos.PageResult;
import com.usian.common.enums.AppHttpCodeEnum;
import com.usian.common.exception.LeadException;
import com.usian.common.threadlocal.UserThreadLocalUtils;
import com.usian.model.media.dtos.WmMaterialDto;
import com.usian.wemedia.entity.WmMaterial;
import com.usian.wemedia.entity.WmNewsMaterial;
import com.usian.wemedia.mapper.WmMaterialMapper;
import com.usian.wemedia.service.IWmMaterialService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.usian.wemedia.service.IWmNewsMaterialService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;

import java.util.Date;
import java.util.List;

/**
 * <p>
 * 自媒体图文素材信息表 服务实现类
 * </p>
 *
 * @author usian
 * @since 2022-10-04
 */
@Service
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements IWmMaterialService {

    @Autowired
    private OSSService ossService;

    @Override
    public String uploadPic(MultipartFile file) {
        //判断参数
        if(file==null){
            throw new LeadException(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //获取用户id
        Integer userId = UserThreadLocalUtils.getUserId();
        if(userId==null){
            //说明用户未登录，需要登录
            throw new LeadException(AppHttpCodeEnum.NEED_LOGIN);
        }

        try {
            //文件上传
            String url = ossService.upload(file);
            WmMaterial wmMaterial = new WmMaterial();
            wmMaterial.setUrl(url);
            wmMaterial.setType(0);
            wmMaterial.setUserId(userId);
            wmMaterial.setIsCollection(false);//新上传的图片，默认都没有收藏
            wmMaterial.setCreatedTime(new Date());
            boolean b = this.save(wmMaterial);
            if(!b){
                throw new LeadException(AppHttpCodeEnum.SERVER_ERROR,"保存素材失败");
            }

        } catch (Exception e) {
            e.printStackTrace();
            throw new LeadException(AppHttpCodeEnum.SERVER_ERROR,"图片上传失败");
        }

        return null;
    }

    @Override
    public PageResult<WmMaterial> findPage(WmMaterialDto dto) {
        if(dto==null){
            throw new LeadException(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //封装分页条件
        Page<WmMaterial> page = new Page<>(dto.getPage(),dto.getSize());
        QueryWrapper<WmMaterial> queryWrapper = new QueryWrapper<>();
        //获取用户id
        Integer userId = UserThreadLocalUtils.getUserId();
        if(userId==null){
            //说明用户未登录，需要登录
            throw new LeadException(AppHttpCodeEnum.NEED_LOGIN);
        }
        queryWrapper.lambda().eq(WmMaterial::getUserId,userId);


        //封装查询条件(是否收藏）
        String isCollection = dto.getIsCollection();

        if(StringUtils.isNotBlank(isCollection)){
            queryWrapper.lambda().eq(WmMaterial::getIsCollection,isCollection);
        }

        //执行查询
        IPage<WmMaterial> iPage = this.page(page, queryWrapper);
        List<WmMaterial> materialList = iPage.getRecords();
        if(CollectionUtils.isEmpty(materialList)){
            throw new LeadException(AppHttpCodeEnum.DATA_NOT_EXIST);
        }

        //返回结果
        return new PageResult<>(dto.getPage(),dto.getSize(),iPage.getTotal(),materialList);
    }

    @Override
    public void updateCollection(Integer id, boolean isCollection) {
        UpdateWrapper<WmMaterial> updateWrapper = new UpdateWrapper<>();
        //获取用户id
        Integer userId = UserThreadLocalUtils.getUserId();
        if(userId==null){
            //说明用户未登录，需要登录
            throw new LeadException(AppHttpCodeEnum.NEED_LOGIN);
        }

        //根据id和用户id，更新收藏状态
        updateWrapper.lambda().eq(WmMaterial::getId,id).eq(WmMaterial::getUserId,userId).set(WmMaterial::getIsCollection,isCollection);
        boolean b = this.update(updateWrapper);
        if(!b){
            throw new LeadException(AppHttpCodeEnum.SERVER_ERROR,"更新收藏状态失败");
        }
    }

    @Autowired
    private IWmNewsMaterialService wmNewsMaterialService;

    @Override
    public void deleteMaterial(Integer id) {
        if(id==null){
            throw new LeadException(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //查询素材是否被文章引用
        QueryWrapper<WmNewsMaterial> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(WmNewsMaterial::getMaterialId,id);
        List<WmNewsMaterial> newsMaterialList = wmNewsMaterialService.list(queryWrapper);
        if(!CollectionUtils.isEmpty(newsMaterialList)){
            //素材被文章引用，不能删除
            throw new LeadException(AppHttpCodeEnum.DATA_EXIST,"素材被文章引用，不能删除");
        }

        //查询素材数据，获取素材图片名称，根据图片名称删除OSS上图片信息
        //获取用户id
        Integer userId = UserThreadLocalUtils.getUserId();
        if(userId==null){
            //说明用户未登录，需要登录
            throw new LeadException(AppHttpCodeEnum.NEED_LOGIN);
        }

        QueryWrapper<WmMaterial> materialQueryWrapper = new QueryWrapper<>();
        materialQueryWrapper.lambda().eq(WmMaterial::getUserId,userId).eq(WmMaterial::getId,id);
        WmMaterial wmMaterial = this.getOne(materialQueryWrapper);
        if(wmMaterial==null){
            throw new LeadException(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //根据图片名称删除OSS上图片信息
        String url = wmMaterial.getUrl();
        String imageName = StringUtils.substringAfterLast(url, "/");
        ossService.deleteFile(imageName);

        //删除素材数据
        boolean b = this.removeById(id);
        if(!b){
            throw new LeadException(AppHttpCodeEnum.SERVER_ERROR,"删除素材数据失败");
        }
    }
}
